using Domain;
using ErrorCode;
using MediatR;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WriteAPI.Command.生产计划;

namespace WriteAPI.CommandHandle.生产计划
{
    /// <summary>
    /// 扩展的生产计划查询命令处理程序
    /// </summary>
    public class GetProductionPlanExtendedCommandHandler : IRequestHandler<GetProductionPlanExtendedCommand, APIPaging<ProductionPlanViewModel>>
    {
        private readonly ISqlSugarClient _db;

        public GetProductionPlanExtendedCommandHandler(ISqlSugarClient db)
        {
            _db = db;
        }

        public async Task<APIPaging<ProductionPlanViewModel>> Handle(GetProductionPlanExtendedCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<ProductionPlanViewModel>();

            try
            {
                // 构建主表查询
                var query = _db.Queryable<Lwp_ProductionPlan>()
                    .WhereIF(!string.IsNullOrEmpty(request.Keyword), p => 
                        p.DocNumber.Contains(request.Keyword) || 
                        p.VersionDesc.Contains(request.Keyword))
                    .WhereIF(request.StartDate.HasValue, p => p.DocDate >= request.StartDate.Value)
                    .WhereIF(request.EndDate.HasValue, p => p.DocDate <= request.EndDate.Value)
                    .WhereIF(!string.IsNullOrEmpty(request.RelatedProject), p => p.BizUser.Contains(request.RelatedProject));

                // 获取总记录数
                var totalCount = await query.CountAsync();
                result.TotalCount = totalCount;
                result.TotalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);

                // 获取分页数据
                var plans = await query
                    .OrderByDescending(p => p.Id)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync();

                // 获取所有计划的明细数据
                var planIds = plans.Select(p => p.Id).ToList();
                var details = await _db.Queryable<ProductionPlanDetail>()
                    .Where(d => planIds.Contains(d.PlanId))
                    .ToListAsync();

                // 转换为视图模型
                var viewModels = new List<ProductionPlanViewModel>();
                foreach (var plan in plans)
                {
                    var planDetails = details.Where(d => d.PlanId == plan.Id).ToList();
                    var firstItem = planDetails.FirstOrDefault();
                    var itemCount = planDetails.Count;

                    var viewModel = new ProductionPlanViewModel
                    {
                        Id = plan.Id,
                        PlanNumber = plan.DocNumber,
                        PlanTheme = plan.VersionDesc,
                        PlanDate = plan.DocDate,
                        ItemDesc = itemCount > 0 
                            ? $"{firstItem?.ItemName} 等{itemCount}项" 
                            : "无物品",
                        HasMore = itemCount > 1,
                        ItemCount = itemCount,
                        RelatedProject = plan.BizUser,
                        Remarks = plan.Remark,
                        SalesOrder = plan.BizNumber,
                        TotalQuantity = plan.TotalQuantity
                    };

                    viewModels.Add(viewModel);
                }

                result.Items = viewModels;
                result.Success = true;
                result.Code = 200;
                result.Message = "查询成功";
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Code = 500;
                result.Message = $"查询生产计划失败: {ex.Message}";
            }

            return result;
        }
    }
} 